<?php

declare(strict_types=1);

namespace App\Controller;

use App\Constants\ErrorCode;
use App\Library\Common;
use App\Model\data\CurrentShopData;
use App\Model\FlyOrder;
use App\Service\PayService;
use App\Service\ShopSendAddressService;
use App\Service\DadaService;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Validation\Rule;
use function _PHPStan_76800bfb5\RingCentral\Psr7\str;

class DadaController extends AbstractController
{

    /**
     * @Inject
     * @var PayService
     */
    private $payService;

    /**
     * @Inject
     * @var DadaService
     * */

    private $dada;

    /**
     * @Inject
     * @var ShopSendAddressService
     */
    private $sendAddress;

    //    获取发货记录
    public function send_list()
    {
        $list = $this->dada->send_order_list();
//        $city_list =  array_column($list,'cityCode','cityName');
        return $this->jsonResponse->success($list,'获取发货记录列表');
    }

//    回调
    public function call_back()
    {
        $request_p =  $this->request->inputs(['signature','client_id','order_id','order_status','cancel_reason','cancel_from','dm_id','dm_name','dm_mobile','finish_code','update_time']);
        $this->validation($request_p,
            [
                'signature'=>[
                    'required',
                    "string",
                ],
                'client_id'=>[
                    "string",
                    "max:50",
                ],
                'order_status'=>'integer',
//                'order_id'=>'required|string|exists:fly_order',
                'order_id'=>[
                    Rule::exists('fly_order','order_sn'),
                    "required",
                    "string",
                ],
                'cancel_reason'=>[
                    Rule::requiredIf($request_p['order_status']==5),
                    "string",
                    "max:50",
                ],
                'cancel_from'=>'required|integer',
                'update_time'=>'required|integer',
            ],
            );

        $res = $this->dada->check_sign($request_p);
        if($res==true){
            if ($this->dada->call_back($request_p)){
                return $this->jsonResponse->success(ErrorCode::SYSTEM_INVALID,'处理完成');
            }else{
                return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'处理失败');
            }
        }else{
           return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'签名校验失败');
        }
    }

    //    取消下单
    public function cancel()
    {
        $request_p = $this->request->inputs(['id','order_sn','cancel_reason_id','cancel_reason']);
        $shop_info =  CurrentShopData::getData();
        $this->validation($request_p,
            [
                'id'=>[
                    Rule::exists('fly_shop_dada_order','id'),
                    "integer",
                ],
                'cancel_reason_id'=>[
                    Rule::in([1,2,3,4,5,34,35,36,37,10000]),
                    "integer",
                ],
                'cancel_reason'=>[
                    Rule::requiredIf($request_p['cancel_reason_id']==10000),
                    "string",
                    "max:50",
                ],
                'order_sn'=>[
                    'required',
                    'string',
                    Rule::exists('fly_order','order_sn')
                        ->where('shop_id',$shop_info->id)
                        ->where('order_type',1)
                        ->where('delivery_type',3),
                    Rule::exists('fly_delivery_send_order','order_sn')
                        ->where('delivery_type','dada')
                        ->where('is_cancel','0')
                        ->where('service_type',2)
                        ->whereNull('deleted_at'),
                ]
            ],
            );
        return $this->jsonResponse->success($this->dada->cancel_order($request_p,$shop_info->id),'订单取消');
    }

//    城市列表
    public function city_list()
    {
        $list = $this->dada->get_city_list();
        return $this->jsonResponse->success($list,'获取城市列表');
    }
    //    检测城市
    public function check_city()
    {
        $request_p = $this->request->inputs(['address']);
        $this->validation($request_p,
            [
                'address'=>[
                    "required",
                    "string",
                    "max:50",
                ],
            ],
        );
        $res = $this->dada->check_city($request_p['address']);
        return $this->jsonResponse->success($res,'此城市是否开通达达');
    }

//    询价下单
    public function add_order()
    {
        $request_p = $this->request->inputs(['order_sn','type','num']);
        $shop_info =  CurrentShopData::getData();
        var_dump($shop_info->id);
        $this->validation($request_p,
            [
                'type'=>'min:1|max:2|required|integer',
                'num'=>[
                    Rule::requiredIf($request_p['type']==1),
                    "string",
                    "max:50",
                ],
                'order_sn'=>[
                    'required',
                    'string',
                    Rule::exists('fly_order','order_sn')
                        ->where('shop_id',$shop_info->id)
                        ->where('order_type',1)
                        ->where('delivery_type',3),
                    Rule::unique('fly_poll_log','order_sn')
                        ->where('com','dada')
                        ->where('send_type',2)
                        ->where('order_type',1),
                    Rule::unique('fly_delivery_send_order','order_sn')
                        ->where('delivery_type','dada')
                        ->where('service_type',2)
                        ->whereNull('deleted_at'),
                ]
            ],
        );
        $order_info = FlyOrder::query()
            ->with('with_address_info')
            ->with('with_products')
            ->where('order_sn',$request_p['order_sn'])->first()->toArray();
        $city_list = $this->dada->get_city_list();


        $city_list = array_column($city_list,'cityCode','cityName');
        if($order_info['with_address_info']==''){
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'收货地址不完整,请稍后重新询价');
        }
        $city_name = Common::cut('省','市',$order_info['with_address_info']['street_str']);
        if(isset($city_list[$city_name])){
            $city_code = $city_list[$city_name];
        }else{
            $city_code = '0000';
        }
        $param = array (
            "shop_no"=>strval($shop_info->id),
            "origin_id"=>$order_info['order_sn'],
            "city_code"=>strval($city_code),
            "cargo_price"=> doubleval($order_info['paid_price']),
            "is_prepay"=> 0,
            "receiver_name"=>$order_info['with_address_info']['link_name'],
            "receiver_phone"=>$order_info['with_address_info']['phone'],
            "receiver_address"=> $order_info['with_address_info']['street_str'].$order_info['with_address_info']['address_info'],
            "info"=> $order_info['remark'],
            "origin_mark"=> $order_info['remark'],
            "origin_mark_no"=> "#辅链云商城#{$order_info['order_sn']}#",
            "receiver_lng"=> doubleval($order_info['with_address_info']['lng']) ,
            "receiver_lat"=>doubleval($order_info['with_address_info']['lat']),
            "cargo_weight"=> doubleval(1),
            "callback"=> 'http://dev3.gongfuc.com/api/lsk-ydproduct/api/v1/dada/call_back?type=dada',
        );
        if($request_p['type']==1){
//            询价后下单
            $price_redis =  $this->dada->redis_get('dada_price-'.$param['origin_id']);
            if(!$price_redis){
                return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'询价超时,请稍后重新询价');
            }
            if(!$this->dada->check_balance($price_redis['deliverFee'],$shop_info->id)){
                return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'余额不足，请先充值后下单');
            };
            Db::beginTransaction();
            try {
                $res1 =  $this->dada->insert_order($param,$order_info,$this->getAdminId());
                $res2 =  $this->dada->after_price_add(['deliveryNo'=>$price_redis['deliveryNo']]);
//                $res2 = ['result'=>[],'status'=>'success','msg'=>'111'];
                if($res1&&$res2){
                    $this->dada->createDadaPayOrder($shop_info->id,$order_info,float($price_redis['deliverFee']),$price_redis['deliveryNo']);
                    Db::commit();
//                    return $this->jsonResponse->success($res2,'下单成功');
                    if($res2['status']!='fail'){
                        Db::commit();
                        return $this->jsonResponse->success($res2['result'],'下单成功');
                    }else{
                        Db::rollBack();
                        return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'下单失败-'.$res2['msg']);
                    }
                }else{
                    Db::rollBack();
                    return $this->jsonResponse->error(ErrorCode::SERVER_ERROR,'下单失败-'.$res2['msg']);
                }
            } catch (\Throwable $exception) {
                Db::rollBack();
                return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'下单失败-'.$exception->getMessage());
            }
        }else{
            //询价 缓存redis
            try {
                $res1 =  $this->dada->check_price($param);
                var_dump($res1);
                if($res1){
                    if(isset($res1['status'])&&$res1['status']!='fail'){
                        return $this->jsonResponse->success($res1['result'],'询价成功');
                    }else{
                        return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'询价失败'.$res1['msg']);
                    }
                }else{
                    return $this->jsonResponse->error(ErrorCode::SERVER_ERROR,'询价失败-');
                }
            } catch (\Throwable $exception) {
                return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'询价失败.'.$exception->getMessage());
            }

        }

    }


    public function open_station(){
        $shop_info = CurrentShopData::getData();
////        检测开通达达门店
       if($this->dada->check_shop(intval($shop_info->id))){
           return $this->jsonResponse->error(ErrorCode::SERVER_ERROR,'已开通权限请勿重复开通');
       }
        $param = array (
                "station_name"=>$shop_info->shop_name.time(),
//                "city_name"=> '驻马店市',
                "business"=> ($shop_info->shop_style==2)?1:5,
//                "area_name"=> '南湖区',
                "station_address"=> $shop_info->address_locate,
                "lng"=> doubleval($shop_info->lng) ,
                "lat"=>doubleval($shop_info->lat),
                "contact_name"=> $shop_info->link_name,
                "phone"=> $shop_info->phone,
                "origin_shop_id"=> strval($shop_info->id),
//                "origin_shop_id"=> 89,
        );

        try {
            $res2 =  $this->dada->open_station($param);
            if($res2['status']=='fail'){
//                数据库记录
                Db::beginTransaction();
                $res =  $this->dada->insert_station($param,$this->getAdminId());
                if($res){
    //                达达接口开通
                    Db::commit();
                    return $this->jsonResponse->success($res2['result'],'开通成功');
                }else{
                    return $this->jsonResponse->error(ErrorCode::SERVER_ERROR,'开通失败-'.$res['msg']);
                }
            }else{
                return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'开通失败或已开通');
            }
        } catch (\Throwable $exception) {
            Db::rollBack();
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'开通失败.'.$exception->getMessage());
        }
    }

    public function close_station(){
        $shop_info = CurrentShopData::getData();
//       if($this->dada->check_shop(intval($shop_info->id))){
//           return $this->jsonResponse->error(ErrorCode::SERVER_ERROR,'已开通权限请勿重复开通');
//       }
        $param = array (
            "station_name"=>$shop_info->shop_name,
//                "city_name"=> '嘉兴市',
//                "area_name"=> '南湖区',
            "station_address"=> $shop_info->address_locate,
            "lng"=> doubleval($shop_info->lng) ,
            "lat"=>doubleval($shop_info->lat),
            "contact_name"=> $shop_info->link_name,
            "phone"=> $shop_info->phone,
            "origin_shop_id"=> strval($shop_info->id),
        );

        try {
            $res2 =  $this->dada->open_station($param);
            if($res2['status']=='fail'){
//                数据库记录
                Db::beginTransaction();
                $res =  $this->dada->insert_station($param,$this->getAdminId());
                if($res){
                    //                达达接口开通
                    Db::commit();
                    return $this->jsonResponse->success($res2['result'],'开通成功');
                }else{
                    return $this->jsonResponse->error(ErrorCode::SERVER_ERROR,'开通失败-'.$res['msg']);
                }
            }else{
                return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'开通失败或已开通');
            }
        } catch (\Throwable $exception) {
            Db::rollBack();
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'开通失败.'.$exception->getMessage());
        }
    }
    //    达达门店详情
    public function station_info(){
        $shop_info = CurrentShopData::getData();
        return $this->jsonResponse->success($this->dada->get_station(intval($shop_info->id)),'门店详情.');
    }

    //    修改达达门店
    public function edit_station(){
        $request_p = $this->request->inputs(['id','station_name','phone','contact_name','station_address','lng','lat']);
        $shop_info =  CurrentShopData::getData();
        $this->validation($request_p,
            [
                'id'=>[
                    "integer",
                    'required',
                    Rule::exists('fly_dada_shop','id')->where('origin_shop_id',$shop_info->id)
                ],
                'station_name'=>["string","required","max:50"],
                'phone'=>["string","required","max:20"],
                'contact_name'=>["string","required","max:50"],
                'station_address'=>["string","required","max:255"],
                'lng'=>["string","required","max:50"],
                'lat'=>["string","required","max:50"],
            ],
            );
        $request_p['origin_shop_id'] = $shop_info->id;
        return $this->jsonResponse->success($this->dada->edit_station(Common::filter_null($request_p)),'修改达达门店');

    }

    public function dada_order_info()
    {
        $request_p = $this->request->inputs(['order_sn']);
        $this->validation($request_p,
            [
                'order_sn'=>[
                    "integer",
                    'required',
                ],
            ],
            );
        return $this->jsonResponse->success($this->dada->order_info($request_p['order_sn']),'达达订单详情');
    }

    /**
     * 生成达达充值单
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function rechargeCreate()
    {
        $shop_info = CurrentShopData::getData();
        $amount = (int)$this->request->input('amount', 0);

        if (empty($amount)) {
            return $this->jsonResponse->error(ErrorCode::NORMAL_ERROR, '请选择充值金额');
        }
        if ($amount % 50 != 0) {
            return $this->jsonResponse->error(ErrorCode::NORMAL_ERROR, '充值金额错误');
        }
        $pay_sn = $this->dada->rechargeCreate((int)$shop_info->id, $amount);
        if (empty($pay_sn)) {
            return $this->jsonResponse->error(ErrorCode::NORMAL_ERROR, '订单生成失败！');
        }
        return $this->jsonResponse->success(['pay_sn' => $pay_sn], '成功');
    }

    /**
     * 达达商家充值支付
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function dadaPay()
    {
        $shop_info = CurrentShopData::getData();
        $sn = (string)$this->request->input('order_sn', '');
        if (empty($shop_info) || empty($sn)) {
            return $this->jsonResponse->error(ErrorCode::NORMAL_ERROR, '缺少参数');
        }
        $params = $this->request->all();
        $params['user_id'] = (int)$this->getAdminId();
        // 支付参数验证
        $pay_v = $this->payService->payVerify($params);
        if (!$pay_v['res']) {
            return $this->jsonResponse->error(ErrorCode::NORMAL_ERROR, $pay_v['msg']);
        }
        $pay_res = $this->payService->submit($pay_v['data']);
        return $this->jsonResponse->success($pay_res);
    }

    /***
 *                                         ,s555SB@@&
 *                                      :9H####@@@@@Xi
 *                                     1@@@@@@@@@@@@@@8
 *                                   ,8@@@@@@@@@B@@@@@@8
 *                                  :B@@@@X3hi8Bs;B@@@@@Ah,
 *             ,8i                  r@@@B:     1S ,M@@@@@@#8;
 *            1AB35.i:               X@@8 .   SGhr ,A@@@@@@@@S
 *            1@h31MX8                18Hhh3i .i3r ,A@@@@@@@@@5
 *            ;@&i,58r5                 rGSS:     :B@@@@@@@@@@A
 *             1#i  . 9i                 hX.  .: .5@@@@@@@@@@@1
 *              sG1,  ,G53s.              9#Xi;hS5 3B@@@@@@@B1
 *               .h8h.,A@@@MXSs,           #@H1:    3ssSSX@1
 *               s ,@@@@@@@@@@@@Xhi,       r#@@X1s9M8    .GA981
 *               ,. rS8H#@@@@@@@@@@#HG51;.  .h31i;9@r    .8@@@@BS;i;
 *                .19AXXXAB@@@@@@@@@@@@@@#MHXG893hrX#XGGXM@@@@@@@@@@MS
 *                s@@MM@@@hsX#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&,
 *              :GB@#3G@@Brs ,1GM@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@B,
 *            .hM@@@#@@#MX 51  r;iSGAM@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@8
 *          :3B@@@@@@@@@@@&9@h :Gs   .;sSXH@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@:
 *      s&HA#@@@@@@@@@@@@@@M89A;.8S.       ,r3@@@@@@@@@@@@@@@@@@@@@@@@@@@r
 *   ,13B@@@@@@@@@@@@@@@@@@@5 5B3 ;.         ;@@@@@@@@@@@@@@@@@@@@@@@@@@@i
 *  5#@@#&@@@@@@@@@@@@@@@@@@9  .39:          ;@@@@@@@@@@@@@@@@@@@@@@@@@@@;
 *  9@@@X:MM@@@@@@@@@@@@@@@#;    ;31.         H@@@@@@@@@@@@@@@@@@@@@@@@@@:
 *   SH#@B9.rM@@@@@@@@@@@@@B      @@@          3@@@@@@@@@@@@@@@@@@@@@@@@@@5
 *     ,:.   9@@@@@@@@@@@#HB5   @@@@@           .M@@@@@@@@@@@@@@@@@@@@@@B
 *           ,ssirhSM@&1;i19911i,.             s@@@@@@@@@@@@@@@@@@@@@@@@@@S
 *              ,,,rHAri1h1rh&@#353Sh:          8@@@@@@@@@@@@@@@@@@@@@@@@@#:
 *            .A3hH@#5S553&@@#h   i:i9S          #@@@@@@@@@@@@@@@@@@@@@@@@@A.
 *
 *
 *    妈妈，再爱我一次！
 */
}
